package com.wiki.gds.user.provider.security.oauth2.core.service;

import com.wiki.gds.base.common.exception.BizExceptionEnum;
import com.wiki.gds.base.common.exception.BusinessException;
import com.wiki.gds.base.common.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;

@Component
public class LoginAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    IntegrationUserDetailsService userDetailsService;

    private PasswordEncoder passwordEncoder;
    public LoginAuthenticationProvider(IntegrationUserDetailsService userDetailsService) {
        super();// 这个地方一定要对userDetailsService赋值，不然userDetailsService是null (这个坑有点深)

        setUserDetailsService(userDetailsService);
    }
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            String presentedPassword = authentication.getCredentials().toString();
            presentedPassword= MD5Util.getMd5Value(presentedPassword);
            if (!(presentedPassword.equals(userDetails.getPassword()))) {
                this.logger.debug("Authentication failed: password does not match stored value");
                throw new OAuth2Exception(BizExceptionEnum.LOGIN_PASSWORD_ERROR.getMessage());
            }
        }
    }


}
